<template>
  <div class="contactInfo-container">
    <!-- 主体区域开始 -->
    <v-card
      v-if="company && contactInfo && companyBackFill && contactInfoBackFill"
    >
      <v-tooltip bottom>
        <template v-slot:activator="{ on }">
          <v-btn v-on="on" @click="openSave" class="save-btn" icon>
            <v-icon color="#fff">mdi-content-save</v-icon>
          </v-btn>
        </template>
        Save Contact Info
      </v-tooltip>
      <v-card class="content pt-4">
        <!-- 表单开始 -->
        <div class="form">
          <v-row class="ml-4" no-gutters>
            <v-col cols="1" class="label"> Entity Number </v-col>
            <v-col cols="3" class="input text-left">
              <v-text-field
                v-model="companyBackFill.entityNumber"
                v-validate="'required'"
                name="Entity Number"
                class="white-input"
                solo
                hide-details
                dense
              ></v-text-field>
              <span class="vee-validate-error">
                {{ errors.first("Entity Number") }}
              </span>
            </v-col>
          </v-row>
          <v-row class="mt-4 ml-4" no-gutters>
            <v-col cols="1" class="label"> Entity Type </v-col>
            <v-col cols="3" class="input text-left">
              <v-select
                v-model="companyBackFill.entityType"
                :items="entityTypes"
                v-validate="'required'"
                name="Entity Type"
                class="white-input"
                solo
                dense
                hide-details
              ></v-select>
              <span class="vee-validate-error">
                {{ errors.first("Entity Type") }}
              </span>
            </v-col>
          </v-row>
          <v-row class="mt-4 ml-4" no-gutters>
            <v-col cols="1" class="label">Entity Name </v-col>
            <v-col cols="4" class="pa-0 text-left">
              <v-text-field
                v-model="companyBackFill.entityName"
                v-validate="'required'"
                name="Entity Name"
                class="white-input"
                solo
                dense
                hide-details
              ></v-text-field>
              <span class="vee-validate-error">
                {{ errors.first("Entity Name") }}
              </span>
            </v-col>
          </v-row>
          <v-row class="mt-4 ml-4" no-gutters>
            <v-col cols="1" class="label">Selected location </v-col>
            <v-col
              v-if="selectedAddress"
              cols="10"
              class="pa-0 text-left location-text"
            >
              {{ selectedAddress.locationCode }} - {{ selectedAddress.address }}
            </v-col>
          </v-row>
        </div>
        <!-- 表单结束 -->
        <!-- 右边按钮 -->
        <div class="right-btn">
          <v-btn
            @click="openItems"
            color="#ECEDEE"
            height="64"
            width="64"
            class="mr-4"
            depressed
          >
            <v-icon color="#79839B">mdi-clipboard-text</v-icon>
            <span class="btn-font">Items</span>
          </v-btn>
          <v-btn
            @click="openSetting"
            color="#ECEDEE"
            height="64"
            width="64"
            depressed
          >
            <v-icon color="#79839B">mdi-account-cog</v-icon>
            <span class="btn-font">Setting</span>
          </v-btn>
        </div>
        <!-- Contact Person开始 -->
        <ContactPerson
          :contactPersons="contactInfoBackFill.contactPersons"
        ></ContactPerson>
        <!-- Contact Person结束 -->
        <!-- Contract 开始 -->
        <Contract :contracts="contactInfoBackFill.contracts"></Contract>
        <!-- Contract 结束 -->
        <Dialog
          v-model="showDialog"
          @submit="dialogSave"
          :title="dialogTitle"
          :width="dialogWidth"
        >
          <template #headerAppend="{ close }">
            <v-icon v-if="step === 1" color="#fff" size="18" class="mr-4">
              mdi-file-send
            </v-icon>
            <v-icon
              v-if="step !== 3"
              @click="dialogSave"
              color="#fff"
              size="18"
              class="mr-4"
            >
              mdi-content-save
            </v-icon>
            <v-icon @click="close" color="#fff" size="18">mdi-close</v-icon>
          </template>
          <template>
            <Items
              v-if="step === 1 && itemsBackfill"
              :itemsInfo="itemsBackfill"
            ></Items>
            <Setting
              v-else-if="step === 2 && settingBackfill"
              :settingInfo="settingBackfill"
              ref="setting"
            ></Setting>
            <Save
              v-else-if="step === 3"
              @submit="saveContactInfo"
              :subtitle="saveSubtitle"
            ></Save>
          </template>
        </Dialog>
      </v-card>
    </v-card>
  </div>
</template>

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import Contract from "@/components/Customer/ContactInfo/Contract.vue";
import ContactPerson from "@/components/Customer/ContactInfo/ContactPerson.vue";
import Setting from "@/components/Customer/Dialog/Setting/Setting.vue";
import Items from "@/components/Customer/Dialog/Items/Items.vue";
import Save from "@/components/Customer/Dialog/Save/Save.vue";
import Dialog from "@/components/Maintenance/Dialog/Dialog.vue";
import {
  IEntity,
  IContactInfo,
  ICompany,
  IItems,
  ISetting,
} from "@/components/Customer/index";
import { Route, NavigationGuardNext } from "vue-router";
import { store } from "@/store/index";
import { ContactInfoStore } from "@/store/CustomerStore/ContactInfoStore/ContactInfoStore";
import { routeMapping } from "@/router/index";
type state = typeof store.state;
interface IContactInfoStore extends state {
  ContactInfoStore: typeof ContactInfoStore.state;
}
@Component({
  components: {
    Contract,
    ContactPerson,
    Setting,
    Items,
    Save,
    Dialog,
  },
  beforeRouteEnter(to: Route, from: Route, next: NavigationGuardNext) {
    const state = store.state as IContactInfoStore;
    const selectedCompany = state.ContactInfoStore.selectedCompany;
    // 判断是否存在contactInfo数据没有则跳转到Existing
    if (selectedCompany) {
      next();
    } else {
      next({ name: routeMapping.Customer.ExistingCustomer });
    }
  },
})
export default class ContactInfo extends Vue {
  companyBackFill: ICompany | null = null;
  get company(): ICompany {
    const selectedCompany = this.$store.state.ContactInfoStore.selectedCompany;
    this.$set(
      this,
      "companyBackFill",
      JSON.parse(JSON.stringify(selectedCompany))
    );
    return selectedCompany;
  }
  set company(company: ICompany) {
    this.$store.commit("ContactInfoStore/setSelectedCompany", company);
  }
  contactInfoBackFill: IContactInfo | null = null;
  get contactInfo(): IContactInfo {
    const contactInfo = this.$store.state.ContactInfoStore.contactInfo;
    this.$set(
      this,
      "contactInfoBackFill",
      JSON.parse(JSON.stringify(contactInfo))
    );
    return contactInfo;
  }
  itemsBackfill: IItems | null = null;
  settingBackfill: ISetting | null = null;
  // 1.items 2.setting 3.SaveContactInfo
  step = -1;
  // Dialog
  dialogTitle = "";
  showDialog = false;
  get dialogWidth() {
    return this.step !== 3 ? "1152" : "480";
  }
  openDialog() {
    this.showDialog = true;
  }
  closeDialog() {
    this.showDialog = false;
  }
  openItems() {
    if (!this.contactInfoBackFill) return;
    this.step = 1;
    this.dialogTitle = "Items";
    this.itemsBackfill = JSON.parse(
      JSON.stringify(this.contactInfoBackFill.items)
    );
    this.openDialog();
  }
  openSetting() {
    if (!this.contactInfoBackFill) return;
    this.step = 2;
    this.dialogTitle = "Setting";
    this.settingBackfill = JSON.parse(
      JSON.stringify(this.contactInfoBackFill.setting)
    );
    this.openDialog();
  }
  get saveSubtitle() {
    if (!this.companyBackFill) return "";
    return `${this.companyBackFill.entityNumber}- ${this.companyBackFill.entityName}`;
  }
  async openSave() {
    this.step = 3;
    this.dialogTitle = "Save";
    const valid: boolean = await this.$validator.validate();
    if (valid) {
      this.openDialog();
    }
  }
  // company
  // basic
  entityTypes = ["Prospect", "Contractor", "Supplier", "Member"];
  get selectedAddress() {
    return this.$store.state.ContactInfoStore.selectedAddress;
  }
  // contract
  async dialogSave() {
    if (!this.contactInfoBackFill) return;
    if (this.step === 1 && this.itemsBackfill) {
      this.contactInfoBackFill.items = this.itemsBackfill;
      this.closeDialog();
    } else if (this.step === 2) {
      const result = await (this.$refs.setting as Setting).validateFormData();
      if (result) {
        this.contactInfoBackFill.setting = result;
        this.closeDialog();
      }
    }
  }
  get entities(): Array<IEntity> {
    return this.$store.state.CustomerStore.entities;
  }
  get companyList(): ICompany[] {
    return this.$store.state.ExistingCustomerStore.companyList;
  }
  async saveContactInfo() {
    if (!this.companyBackFill) return;
    if (!this.companyBackFill.id) {
      this.companyBackFill.id = String(new Date().getTime());
    }
    let entityTypeSame = false;
    if (this.company.entityType === this.companyBackFill.entityType) {
      entityTypeSame = true;
    }
    this.companyBackFill.addressTree.every((address) => {
      if (address.id === this.selectedAddress.id) {
        Object.assign(address.contactInfo, this.contactInfoBackFill);
        return false;
      }
    });
    if (!entityTypeSame) {
      // entityType发生了改变则将数据从原companyList中移除
      const isFoundEntity = this.entities.some((entity) => {
        if (entity.entityType === this.company.entityType) {
          const companyIndex = entity.companyList.findIndex((company) => {
            return company.id === this.company.id;
          });
          entity.companyList.splice(companyIndex, 1);
          return false;
        }
        // entity是否有跟companyBackFill对应的entityType
        if (
          entity.entityType === (this.companyBackFill as ICompany).entityType
        ) {
          entity.companyList.push(this.companyBackFill as ICompany);
          return true;
        }
      });
      if (!isFoundEntity) {
        this.entities.push({
          id: String(new Date().getTime()),
          entityType: this.companyBackFill.entityType,
          companyList: [this.companyBackFill],
        });
      }
    }
    Object.assign(this.company, this.companyBackFill);
    this.SweetAlertService.success("Save successfully");
    this.closeDialog();
  }
}
</script>

<style lang="scss" scoped>
@import "@/views/04000000-Customer/ContactInfo/ContactInfo.scss";
</style>
